<template>
  <el-card shadow="never">
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 主题区域 -->
    </div>
    <div class="filter-bar">
      <!-- 搜素区域 -->
      <div class="l-form">
        <el-input placeholder="请输入内容" size="small" v-model="query" clearable @clear="getUserList">
          <template slot="append">
            <i class="el-icon-search" @click="searchUser"></i>
          </template>
        </el-input>
      </div>
      <!-- 添加区域 -->
      <div class="r-btn">
        <el-button type="primary" size="small" @click="addDialogShow = true">增加</el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column width="100" prop="mg_state" label="状态" align="center">
          <template slot-scope="scope">
            <!-- 使用cahnge事件触发,用scope.row.方法获取id传送,用事件对象发送状态 -->
            <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row.id, $event)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="注册时间" align="center">
          <template slot-scope="scope">{{ scope.row.create_time | formateTime() }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="editUser(scope.row.id)"
              circle
            ></el-button>
            <el-button
              type="warning"
              size="small"
              icon="el-icon-setting"
              @click="setUserRole(scope.row)"
              circle
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="delUser(scope.row.id)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pagesize"
        :page-sizes="[1, 2, 3, 4, 5, 6]"
        @size-change="sizeChange"
        @current-change="pageChange"
      ></el-pagination>
    </div>
    <!-- 增加表单弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogShow" width="50%">
      <el-form
        :model="addForm"
        ref="addForm"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUserSubmit">添加</el-button>
          <el-button type="info" @click="restUserForm('addForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改表单弹框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogShow" width="50%">
      <el-form
        :model="editForm"
        ref="editForm"
        :rules="editRules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editUserSubmit">立即修改</el-button>
          <el-button type="info" @click="restUserForm('editForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 用户授权弹框 -->
    <el-dialog title :visible.sync="setRoleShow" width="30%" @close="rid = ''">
      <p>用户昵称: {{ userinfo.username }}</p>
      <br />
      <p>当前角色: {{ userinfo.role_name }}</p>
      <br />
      <p>
        授权角色:
        <el-select v-model="rid" placeholder="请选择角色">
          <!-- :label 显示文本，:value 选中值 -->
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer">
        <el-button @click="setRoleShow = false">Cancel</el-button>
        <el-button type="primary" @click="setRoleSubmit">OK</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  data() {
    // 邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("情书合法的手机号"));
    };
    return {
      query: "", // 查询参数
      pagenum: 1, // 默认页码
      pagesize: 6, // 获取页数
      userList: [], //列表数据
      total: 0,
      addDialogShow: false,
      editDialogShow: false,
      setRoleShow: false,
      userinfo: {},
      rid: "",
      // 添加表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 修改表单数据
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      // 添加验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 修改验证规则
      editRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      roleList: (state) => state.role.rolelist,
    }),
  },
  //   创建后获取数据,渲染页面
  created() {
    this.getUserList();
    !this.roleList.length && this.get_role_list();
  },
  methods: {
    // 获取角色列表
    ...mapActions({
      get_role_list: "role/get_role_list",
    }),
    // 获取数列表
    async getUserList() {
      //   发送请求
      let { data: res } = await this.$axios.get("users", {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        },
      });
      //   console.log(res);
      // 错误处理
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 删除按钮
    async delUser(id) {
      // 使用 try 确认弹框,确认发送请求,取消跑出错误
      try {
        await this.$confirm("确定删除吗,?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 发送请求
        let { data: res } = await this.$axios.delete("users/" + id);
        // 错误处理
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        // 成功处理;
        this.$message.success("删除成功");
        // 坑:判断是否为第一页,和是否只有一条数据
        if (this.pagenum != 1 && this.userList.length == 1) {
          // 退一页
          this.pagenum--;
        }
        this.getUserList();
        // 取消提示用户
      } catch (error) {
        this.$message.info("取消删除");
      }
    },
    // 编辑按钮
    async editUser(id) {
      // 1.根据id查询对应数据
      let { data: res } = await this.$axios.get("users/" + id);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      // console.log(res);
      // 把数据添加到修改表单
      this.editForm = res.data;
      // 2.打开弹窗
      this.editDialogShow = true;
    },
    // 页面数量更换事件
    sizeChange(val) {
      this.pagesize = val;
      this.getUserList();
    },
    // 页码更换书剑
    pageChange(val) {
      this.pagenum = val;
      this.getUserList();
    },
    // 添加用户提交事件
    async addUserSubmit() {
      // 发送数据添加用户
      let { data: res } = await this.$axios.post("users", this.addForm);
      // 判断
      if (res.meta.status != 201) return this.$message.error(res.meta.msg);
      this.$refs.addForm.resetFields();
      this.addDialogShow = false;
    },
    // 重置事件添加和修改表单
    restUserForm(refName) {
      this.$refs[refName].resetFields(); // 重置表单
      this.addDialogShow = false; // 关闭弹出框
      this.editDialogShow = false;
    },
    // 搜索功能
    searchUser() {
      this.pagenum = 1;
      this.getUserList();
    },
    // 提交修改用户
    editUserSubmit() {
      // 1.验证规则
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return;
        // 2.发送请求
        let { data: res } = await this.$axios.put(
          "users/" + this.editForm.id,
          this.editForm
        );
        // 3.错误处理
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        // 4.成功处理
        this.$message.success("修改成功!");
        // 拉取数据
        this.getUserList();
        // 关闭弹窗
        this.editDialogShow = false;
      });
    },
    // 状态切换
    async changeStatus(id, status) {
      // 发送请求 接收id和状态
      let { data: res } = await this.$axios.put(
        "users/" + id + "/state/" + status
      );
      // 错误处理
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      // 成功处理
      this.$message.success(res.meta.msg);
    },
    // 设置角色按钮
    setUserRole(row) {
      this.setRoleShow = true;
      this.userinfo = row;
    },
    // 设置角色发送数据
    async setRoleSubmit() {
      // 判断用户是否选择了id
      if (!this.rid) return this.$message.error("请选择角色");
      // 发送请求
      //发送请求完成分配角色的操作
      // console.log(this.userinfo.id);
      let { data: res } = await this.$axios.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.rid,
        }
      );
      console.log(res);
      //判断如果删除失败，就做提示
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success("分配角色成功");
      this.getUserList();
      //关闭对话框
      this.setRoleShow = false;
    },
  },
};
</script>

<style lang="less" scoped>
</style>